﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WHLRDF.ORM;
using WHLRDF.Application.Model;
namespace WHLRDF.Application.BLL
{
    public enum RelationUserType
    {
        /// <summary>
        /// 角色
        /// </summary>
        Role=0,
        /// <summary>
        /// 部门
        /// </summary>
        Dept=1,
        /// <summary>
        /// 用户组
        /// </summary>
        Group=2
    }
    public class RelationUserService : SerivceBase, IRelationUserService
    {
        
        #region 基本方法
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<RelationUserEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(RelationUserEntity.__IsDeleted, false);
            return this.Query<RelationUserEntity>(criter).ToList();

        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public RelationUserEntity GetById(string id)
        {
            return this.GetById<RelationUserEntity>(id);

        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Save(RelationUserEntity entity, ref string strError)
        {
            if (string.IsNullOrWhiteSpace(entity.RelationUserId))
            {
                entity.RelationUserId = Guid.NewGuid().ToString();
            }
            return this.SaveOrUpdate(entity);

        }
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
                return this.Delete<RelationUserEntity>(deleteKey,false);
            }
            return true;
        }
        /// <summary>
        /// 分页查询方法
        /// <param name="grid">分页查询的相关参数</param>
        /// </summary>
        public LigerGrid ForGrid(LigerGrid grid)
        {
            ICriterion criter = Expression.Eq("IsDeleted", false);
            if (!string.IsNullOrEmpty(grid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(new string[] {
                                RelationUserEntity._PrimaryKeyName ,
                           }, grid.keyWord)
                           );
            }
            return this.Query<RelationUserEntity>(grid, criter);

        }
        #endregion

        #region 扩展方法
        public List<RelationUserEntity> GetRelationByUserId(string userid,int relationType=0)
        {
            if (string.IsNullOrWhiteSpace(userid))
            {
                return null;
            }
            ICriterion criter = Expression.Eq("IsDeleted", false);
            criter= Expression.And(criter, Expression.Eq(RelationUserEntity.__UserId,userid));
            criter = Expression.And(criter, Expression.Eq(RelationUserEntity.__RelationType, relationType));
            return this.Query<RelationUserEntity>(criter);
        }

        /// <summary>
        /// 保存用户的关联关系
        /// </summary>
        /// <param name="userid">用户id</param>
        /// <param name="itemKeys">键值</param>
        /// <param name="strError"></param>
        /// <param name="relationType">类别</param>
        /// <returns></returns>
        public bool RelationUserSave(string userid, string itemKeys,ref string strError, 
            RelationUserType relationType = RelationUserType.Role)
        {
            if (string.IsNullOrWhiteSpace(userid))
            {
                strError = "参数错误";
                return false;
            }
            ICriterion criter = Expression.Eq("IsDeleted", false);
            criter = Expression.And(criter, Expression.Eq(RelationUserEntity.__UserId, userid));
            criter = Expression.And(criter, Expression.Eq(RelationUserEntity.__RelationType, relationType.GetHashCode()));
            List<RelationUserEntity> lstItem = new List<RelationUserEntity>();
            if (!string.IsNullOrWhiteSpace(itemKeys))
            {
                string[] items = itemKeys.Split(new char[] { ';',','});
                foreach (var item in items)
                {
                    if (!string.IsNullOrWhiteSpace(item))
                    {
                        lstItem.Add(new RelationUserEntity {
                            UserId=userid,
                            RelationType=relationType.GetHashCode(),
                            RelationUserId=Guid.NewGuid().ToString(),
                            ResourceId=item
                        });
                    }
                }
            }
            using (var tran = this.Begin())
            {
                try
                {
                    this.Delete<RelationUserEntity>(criter,false);
                    if (lstItem != null && lstItem.Count > 0)
                    {
                        this.BatchInsert<RelationUserEntity>(lstItem,ref strError);
                    }
                    this.Commit();
                }
                catch (Exception ex)
                {
                    this.Rollback();
                    throw ex;
                }
            }
                return true;
        }

        public LigerGrid ForGridByResourceId(LigerGrid ligerGrid ,string resourceId, int relationType = 0)
        {
            if (string.IsNullOrWhiteSpace(resourceId))
            {
                return null;
            }
            ICriterion criter = Expression.Eq("a.IsDeleted", false);
            if (!string.IsNullOrEmpty(ligerGrid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(new string[] {
                                "a."+RelationUserEntity.__UserId ,
                                UserEntity.__UserName,
                                UserEntity.__Email,
                                UserEntity.__Phone,
                                UserEntity.__RealName
                           }, ligerGrid.keyWord)
                           );
            }
            string hql = "select a.* from "+UserEntity._TableName+" as a inner join "+ RelationUserEntity._TableName + " as b on a.UserId=b.userid where 1=1 {0} ";
            criter = Expression.And(criter, Expression.Eq(RelationUserEntity.__ResourceId, resourceId));
            criter = Expression.And(criter, Expression.Eq(RelationUserEntity.__RelationType, relationType));
            return this.Query<UserEntity>(hql,ligerGrid, criter);
        }

        public bool AddRlUserSave(string resourceId, string itemUsers, ref string strError,
           RelationUserType relationType = RelationUserType.Role)
        {
            if (string.IsNullOrWhiteSpace(resourceId) || string.IsNullOrWhiteSpace(itemUsers))
            {
                strError = "参数错误";
                return false;
            }
            ICriterion criter = Expression.Eq("IsDeleted", false);
            criter = Expression.And(criter, Expression.Eq(RelationUserEntity.__ResourceId, resourceId));
            criter = Expression.And(criter, Expression.Eq(RelationUserEntity.__RelationType, relationType.GetHashCode()));
            List<RelationUserEntity> lstItem = new List<RelationUserEntity>();
            string[] items = itemUsers.Split(new char[] { ';', ',' });

            foreach (var item in items)
            {
                if (!string.IsNullOrWhiteSpace(item))
                {
                    lstItem.Add(new RelationUserEntity
                    {
                        UserId = item,
                        RelationType = relationType.GetHashCode(),
                        RelationUserId = Guid.NewGuid().ToString(),
                        ResourceId = resourceId
                    });
                }
            }

            using (var tran = this.Begin())
            {
                try
                {
                    this.Delete<RelationUserEntity>(Expression.And(criter, Expression.In(RelationUserEntity.__UserId, items)), false);
                    if (lstItem != null && lstItem.Count > 0)
                    {
                        this.BatchInsert<RelationUserEntity>(lstItem, ref strError);
                    }
                    this.Commit();
                }
                catch (Exception ex)
                {
                    this.Rollback();
                    throw ex;
                }
            }
            return true;  
        }
        /// <summary>
        /// 删除关系用户
        /// </summary>
        /// <param name="resourceId">关系id</param>
        /// <param name="itemUsers">用户集合</param>
        /// <param name="strError">错误信息</param>
        /// <param name="relationType">关系类别</param>
        /// <returns></returns>
        public bool RemoveRlUserSave(string resourceId, string itemUsers, ref string strError,
          RelationUserType relationType = RelationUserType.Role)
        {
            if (string.IsNullOrWhiteSpace(resourceId) || string.IsNullOrWhiteSpace(itemUsers))
            {
                strError = "参数错误";
                return false;
            }
            ICriterion criter = Expression.Eq("IsDeleted", false);
            criter = Expression.And(criter, Expression.Eq(RelationUserEntity.__ResourceId, resourceId));
            criter = Expression.And(criter, Expression.Eq(RelationUserEntity.__RelationType, relationType.GetHashCode()));
            List<RelationUserEntity> lstItem = new List<RelationUserEntity>();
            string[] items = itemUsers.Split(new char[] { ';', ',' });
            return this.Delete<RelationUserEntity>(Expression.And(criter, Expression.In(RelationUserEntity.__UserId, items)), false);
        }

        /// <summary>
        /// 获取相应的关系对象
        /// <param name="UserId">用户Id</param>
        /// <param name="userType">用户类别</param>
        /// </summary>
        public List<T> GetRelationByUserId<T>(string UserId, RelationUserType relationUserType) where T : class, new()
        {

            StringBuilder strsql = new StringBuilder();
            string tableName = RoleEntity._TableName;
            string primaryKeyName = RoleEntity._PrimaryKeyName;
            switch (relationUserType)
            {
                case RelationUserType.Group:
                    //tableName = GroupEntity._TableName;
                    //primaryKeyName = GroupEntity._PrimaryKeyName;
                    break;
                case RelationUserType.Role:
                    tableName = RoleEntity._TableName;
                    primaryKeyName = RoleEntity._PrimaryKeyName;
                    break;
                case RelationUserType.Dept:
                    tableName = RoleEntity._TableName;
                    primaryKeyName = RoleEntity._PrimaryKeyName;
                    break;


            }
            strsql.Append("select a.* from " + tableName + "  a inner join " + RelationUserEntity._TableName + " b on a." + primaryKeyName + "=b.ResourceId where 1=1 {0} ");
           // strsql.Append("  where a.IsDeleted=0 and b.UserId=" + UserId + " and b.RelationType=" + relationUserType.GetHashCode());
            ICriterion criterion = Expression.And(Expression.Eq("a." + RelationUserEntity.__IsDeleted, 0),
                Expression.And(Expression.Eq("b."+RelationUserEntity.__UserId,UserId),
                Expression.Eq("b." + RelationUserEntity.__RelationType, relationUserType.GetHashCode())
                ));
            return this.Query<T>(strsql.ToString(), criterion);

        }
        #endregion

    }
}